package com.css.fxfzmh.zcpt.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzmh.logInfo.entity.SLog;
import com.css.fxfzmh.logInfo.entity.SLogParam;
import com.css.fxfzmh.util.CreateGson;
import com.css.fxfzmh.util.PlatformObjectUtils;
import com.css.fxfzmh.util.RestTemplateUtil;
import com.css.fxfzmh.util.StringUtils;
import com.css.fxfzmh.web.PlatformSessionContext;
import com.css.fxfzmh.zcpt.sys.entity.SUser;
import com.css.fxfzmh.zcpt.sys.entity.common.page.Page;
import com.css.fxfzmh.zcpt.sys.service.SUserService;
import com.css.fxfzmh.zcpt.sys.service.SysLogService;
//import com.google.gson.Gson;
import com.google.gson.Gson;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @Author: zhangSongRui
 * @CreateTime: 2023/05/15
 * @Description: 日志查询与写入
 */
@Service
public class SysLogServiceImpl implements SysLogService {
    @Autowired
    private RestTemplateUtil restTemplateUtil;
    @Autowired
    SUserService sUserService;

    // 系统代码
    private static final String sysId = PropsHelper.loadProps("slw-config.properties").getProperty("app.system.id");

    @Override
    public String saveLogs(SLog log) throws Exception {
        // 判断参数以下字段是否有值，若为空获取并设置值
        // 操作人
        if(PlatformObjectUtils.isEmpty(log.getOpName())) {
            String user = sUserService.getSUser(PlatformSessionContext.getUserID());
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            //操作人
            log.setOpName(sUser.getUserName());
        }
        // IP
        if(PlatformObjectUtils.isEmpty(log.getOpIp())) {
            log.setOpIp(getIP());
        }
        // 操作事件类型
        if(PlatformObjectUtils.isEmpty(log.getEventType())) {
            log.setEventType(0); // 统一写普通业务事件
        }
        // 操作结果
        if(PlatformObjectUtils.isEmpty(log.getOpResult())) {
            log.setOpResult("success");
        }
        //系统代码
        if(PlatformObjectUtils.isEmpty(log.getSysId())) {
            log.setSysId(sysId);
        }

        //读取配置文件
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        StringBuilder url = new StringBuilder(configGroup.getProperty("baseRestUrl") + "/slog_dzj/savelogs?");
        url.append("opName=" + URLEncoder.encode(log.getOpName(), "UTF-8"));
        url.append("&opIp=" + URLEncoder.encode(log.getOpIp(), "UTF-8"));
        url.append("&logMemo=" + URLEncoder.encode(log.getLogMemo(), "UTF-8"));
        url.append("&eventType=" + log.getEventType());
        url.append("&opResult=" + log.getOpResult());
        url.append("&sysId="+log.getSysId());
        Map<String, Object> paramMap = new HashMap<>(1);
        //操作人
        paramMap.put("opName", URLEncoder.encode(log.getOpName(), "UTF-8"));
        //操作ip
        paramMap.put("opIp", URLEncoder.encode(log.getOpIp(), "UTF-8"));
        //操作
        paramMap.put("logMemo", URLEncoder.encode(log.getLogMemo(), "UTF-8"));
        //事件类型
        paramMap.put("eventType", log.getEventType());
        //操作结果
        paramMap.put("opResult", log.getOpResult());
        //系统代码
        paramMap.put("sysId", log.getSysId());
        ResponseEntity<String> stringResponseEntity = restTemplateUtil.sendHttpRequest(url.toString(), paramMap);
        return stringResponseEntity.getBody();
    }

    /**
     * 获取id
     *
     * @return
     */
    private static String getIP() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    @Override
    public JSONObject getPage(SLogParam param) throws UnsupportedEncodingException {
        //读取配置文件
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String sysId = configGroup.getProperty("app.system.id");
        StringBuilder url = new StringBuilder(configGroup.getProperty("baseRestUrl") + "/slog_dzj/dirlogs?");
        Map<String, Object> paramMap = new HashMap<>(10);
        if (!PlatformObjectUtils.isEmpty(param.getOpName())) {
            url.append("opName=" + URLEncoder.encode(param.getOpName(), "UTF-8"));
            paramMap.put("opName", URLEncoder.encode(param.getOpName(), "UTF-8"));
        }
        if (!PlatformObjectUtils.isEmpty(param.getEventType())) {
            url.append("&eventType=" + URLEncoder.encode(param.getEventType(), "UTF-8"));
            paramMap.put("eventType", URLEncoder.encode(param.getEventType(), "UTF-8"));
        }
        if (!PlatformObjectUtils.isEmpty(param.getOpBeginDate())) {
            url.append("&opBeginDate=" + param.getOpBeginDate());
            paramMap.put("opBeginDate", param.getOpBeginDate());
        }
        if (!PlatformObjectUtils.isEmpty(param.getOpEndDate())) {
            url.append("&opEndDate=" + param.getOpEndDate());
            paramMap.put("opEndDate", param.getOpEndDate());
        }
//        url.append("&sysId=" + sysId).append("&pageSize=").append(param.getPageSize()).append("&currentPage=" + param.getCurrentPage());
//        paramMap.put("sysId", sysId);
        url.append("&pageSize=").append(param.getPageSize()).append("&currentPage=" + param.getCurrentPage());
        paramMap.put("pageSize", param.getPageSize());
        paramMap.put("currentPage", param.getCurrentPage());
        ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(url.toString(), paramMap);
        JSONObject jsonObject = JSON.parseObject(responseEntity.getBody());
        return jsonObject;
    }
}
